package com.googlecode.gwt_control.client.form;

import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FocusListenerAdapter;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;

/**
 *
 * @author Olafur Gauti Gudmundsson
 */
public class ListBoxField extends Field {

    private final ListBox box;

    public ListBoxField( String id, String title ) {
        this(id, title, null);
    }

    public ListBoxField( String id, String title, FieldValidator validator ) {
        super(id, title, validator);
        box = new ListBox();
        box.setStyleName("listBoxField");

        // make sure change events are captured
        box.addFocusListener(new FocusListenerAdapter() {
            @Override
            public void onLostFocus(Widget w) {
               fireFieldChanged();
            }
        });
        box.addChangeListener(new ChangeListener() {
            public void onChange(Widget w) {
                fireFieldChanged();
            }
        });
    }

    public ListBox getBox() {
        return box;
    }

    public String getValue() {
        return box.getValue(box.getSelectedIndex());
    }

    public void addItem( String label, String value ) {
        box.addItem(label, value);
    }

    public void setSelected( String value ) {
        for ( int i = 0; i < box.getItemCount(); i++ ) {
            if ( box.getValue(i).equals(value) ) {
                box.setSelectedIndex(i);
                return;
            }
        }
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        box.setEnabled(enabled);
        if ( enabled ) {
            box.removeStyleName("disabled");
        } else {
            box.addStyleName("disabled");
        }
    }

    @Override
    public void addToTable(int rowNumber, FlexTable table) {
        super.addToTable(rowNumber, table, box);
    }

}
